# -*- coding: utf-8 -*-

"""
@file    : subsystem_cpu_set.py
@time    : 2022-11-04 11:06:29
@author  : wenjiachen（陈文嘉）
@version : 1.0
@contact : wenjiachen@tencent.com
@desc    : None
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os

from . import fileops
from ._subsystem import Subsystem


def get_memory_info():
    if not os.path.exists("/sys/devices/system/node/"):
        return "0"
    return fileops.read("/sys/devices/system/node/online").strip()


class SubsystemCpuSet(Subsystem):

    """
    CpuSet CGroup subsystem. Provides access to

    cpuset.cpu_exclusive
    cpuset.cpus
    cpuset.mem_exclusive
    cpuset.mem_hardwall
    cpuset.memory_migrate
    cpuset.memory_pressure
    cpuset.memory_pressure_enabled
    cpuset.memory_spread_page
    cpuset.memory_spread_slab
    cpuset.mems
    cpuset.sched_load_balance
    cpuset.sched_relax_domain_level
    """

    NAME = 'cpuset'
    _path_cpu_online = "/sys/devices/system/cpu/online"
    STATS = {
        # str object something like '0', '0-1', and '0-1,3,4'
        'effective_cpus': str,
        'effective_mems': str,
        'memory_pressure': int,
    }
    CONFIGS = {
        'cpu_exclusive': 0,
        # same as 'effective_*' ones
        'cpus': fileops.read(_path_cpu_online).strip(),
        'mem_exclusive': 0,
        'mem_hardwall': 0,
        'memory_migrate': 0,
        'memory_pressure_enabled': 0,
        'memory_spread_page': 0,
        'memory_spread_slab': 0,
        # same as 'cpus'
        'mems': get_memory_info,
        'sched_load_balance': 1,
        'sched_relax_domain_level': -1,
    }

    def get_init_parameters(self, parent_configs):
        params = {}
        params['cpus'] = parent_configs['cpus']
        params['mems'] = parent_configs['mems']
        return params

